package com.ycwl.aiLive_2d.thread;

import com.ycwl.aiLive_2d.exception.BaseException;
import com.ycwl.aiLive_2d.utils.AudioUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author songmingsong
 * @date 2023/7/7
 */
@Slf4j
public class MouthThreadReturnByThreadPool implements Runnable {

    private String uid;
    private String audioPath;
    private Integer index;
    public static Map<String, String> isPaseMap = new HashMap<>();
    public static Queue<Map<Integer, List<Double>>> nullList = new LinkedList<>();
    public static Map<String, Queue<Map<Integer, List<Double>>>> queueMap = new HashMap<>();

    public MouthThreadReturnByThreadPool(String uid, String audioPath, Integer i) {
        this.uid = uid;
        this.audioPath = audioPath;
        this.index = i;
    }

    @Override
    public void run() {
        log.info("[ 线程 ] ->启动语音解析线程");
        List<Double> returnListValue = this.getMouthList(uid);// 格式[1,2,3]

        Map<Integer, List<Double>> map = new HashMap<>();
        map.put(index, returnListValue);

        ArrayList<Map<Integer, List<Double>>> dataList = new ArrayList<>();
        dataList.add(map);

        queueMap.put(uid, nullList);
        synchronized (MouthThreadReturnByThreadPool.class){
            queueMap.get(uid).addAll(dataList);
        }
        log.info("[ 线程 ] ->文件：" + index + "->解析出来的总数据：{}", returnListValue);
        log.info("[ 线程 ] ->文件：" + index + "->解析出来的queueMap：{}", queueMap.toString());
    }

    /**
     * 使用Java代码
     * 获取语音嘴巴弧度数据
     *
     * @return
     */
    private List<Double> getMouthList(String uid) {
        return AudioUtils.processAudio(this.audioPath, uid);
    }

    /**
     * 使用python代码
     * 获取语音嘴巴弧度数据
     *
     * @return
     */
    private Object getMouthListByPython() {
        Map<String, Object> map = new HashMap<>(1);
        Process proc;
        try {
            String wavPath = this.getClass().getResource("/").toString();
            if (wavPath.startsWith("file:")) {
                wavPath = wavPath.substring("file:/".length());
            }
            String pythonPath = wavPath + "/python/mouth.py";
            String[] args1 = new String[]{"python", pythonPath, wavPath + uid + "/streaming_tts.wav"};
            proc = Runtime.getRuntime().exec(args1);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));
            String line = null;
            while ((line = in.readLine()) != null) {
                map.put("data", line);
            }
            in.close();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("嘴行弧度转换异常", 5001);
        }
        return map.get("data");
    }


}
